from collections import *
import re

def parse_class(line: str):
    name, lo1, hi1, lo2, hi2 = re.fullmatch(
        r'(.+): (\d+)-(\d+) or (\d+)-(\d+)', line
    ).groups()
    return (name, int(lo1), int(hi1), int(lo2), int(hi2))

def parse_ticket(line: str):
    return tuple(map(int, line.split(',')))

with open('input.txt') as file:
    classes = []
    my_ticket = None
    nearby_tickets = []

    parts = file.read().split('\n\n')

    for line in parts[0].splitlines():
        classes.append(parse_class(line))

    my_ticket = parse_ticket(parts[1].splitlines()[1])

    for line in parts[2].splitlines()[1:]:
        nearby_tickets.append(parse_ticket(line))
    
    valid_tickets = []

    for ticket in nearby_tickets:
        valid = True
        for field in ticket:
            for _, lo1, hi1, lo2, hi2 in classes:
                if lo1 <= field <= hi1 or lo2 <= field <= hi2:
                    break
            else:
                valid = False
        if valid:
            valid_tickets.append(ticket)
                  
    options = {i: set(range(len(classes))) for i in range(len(classes))}
    
    for ticket in valid_tickets:
        for i, field in enumerate(ticket):
            for j, (_, lo1, hi1, lo2, hi2) in enumerate(classes):
                if not (lo1 <= field <= hi1 or lo2 <= field <= hi2):
                    options[i].remove(j)
    result = 1

    while options:
        remove_keys = []
        remove_vals = set()

        for (i, op) in options.items():
            if len(op) == 1:
                klass = next(iter(op))
                if classes[klass][0].startswith("departure"):
                    result *= my_ticket[i]
                remove_keys.append(i)
                remove_vals.add(klass)
        
        for key in remove_keys:
            options.pop(key)
        
        for vals in options.values():
            vals.difference_update(remove_vals)

    print(result)